package org.example.route.service.impl;

import org.example.route.mapper.CityMapper;
import org.example.route.mapper.ProvinceMapper;
import org.example.route.mapper.StationMapper;
import org.example.route.model.dto.BaseRequest;
import org.example.route.model.dto.CityDTO;
import org.example.route.model.dto.CityQueryDTO;
import org.example.route.model.pojo.City;
import org.example.route.model.pojo.Station;
import org.example.route.model.vo.CityVO;
import org.example.route.service.CityService;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private ProvinceMapper provinceMapper;
    @Autowired
    private StationMapper stationMapper;



    /**
     *
     *
     * AI方法
     *
     * **/
    @Tool(name = "listCity", description = "查询并获取城市的信息，包括城市名称，所在省份名称等，" +
            "如果参数为空就查全部的，如果传来省份的名称，你可以先调用listProvince方法获得provinceId")
    public List<CityVO> list(@ToolParam( description = "城市姓名的模糊查询，比如“上海”，或者“上”")String name,
                             @ToolParam(description = "对应省份的id，比如2")Long provinceId) {


        CityQueryDTO cityQueryDTO = new CityQueryDTO(name,provinceId);
        return list(cityQueryDTO);
    }

    @Override
    public void add(CityDTO cityDTO) {
        cityMapper.add(cityDTO);
    }

    @Override
    public List<CityVO> list(CityQueryDTO cityQueryDTO) {
        List<CityVO> cityVOList = new ArrayList<>();
        List<City> cityList = cityMapper.list(cityQueryDTO);
        for (City city : cityList)
        {
            CityVO cityVO = new CityVO(city.getId(), city.getName(), provinceMapper.getProvinceNameById(city.getProvinceId()));
            cityVOList.add(cityVO);
        }
        return cityVOList;

    }

    @Override
    public void delete(BaseRequest baseRequest) {
        City city = cityMapper.getById(Long.parseLong(baseRequest.getKey()));
        if (Objects.isNull(city))
        {
            throw new RuntimeException("城市不存在");
        }

        List<Station> stationList = stationMapper.getByCityId(city.getId());
        if (!stationList.isEmpty())
        {
            throw new RuntimeException("城市下有站点，不能删除");
        }

        cityMapper.deleteById(city.getId());




    }
}
